# -*- coding: utf-8 -*-
"""
@Time   : 2019/11/21 15:12
@Author : LeeCQ
"""
import os
import re, time
import asyncio
import requests
from HTTP.Downloader1024.common.functions import getHtml

album = './photos/'
# if album not in os.listdir('.'): os.mkdir(album)
header = {'User-Agent': 'Mozilla/5.0 (Windows; U; Windows NT 6.1; en-US; rv:1.9.1.6) Gecko/20091201 Firefox/3.5.6'}


def get_a_photo(photo_url, album_name):
    """

    :param photo_url:
    :param album_name:
    :return:
    """
    local_photo_path = f'{album}/{album_name}/{photo_url[-12:]}'
    if os.path.exists(local_photo_path):
        return 1, local_photo_path
    try:
        open(local_photo_path, 'wb').write(requests.get(photo_url, headers=header).content)
        return 0, local_photo_path
    except FileNotFoundError:
        return -1, local_photo_path


def get_album(album_url):
    """
    获取相册的全部内容； name - photos
    :param album_url:
    :return:
    """
    if not os.path.exists(album): os.mkdir(album)
    head, page = getHtml(album_url, headers=header)
    # album_name = re.findall(r'<title>(.*?)</title>', page)[0]
    # album_name = album_name[:album_name.find('|')]
    album_name = re.findall(r'<span id="subject_tpc">(.*?)</span>', page)[0]
    listURL = re.findall(r'<img src="(.*?)" border="0"', page)
    if not os.path.exists(album+album_name): os.mkdir(album+album_name)
    for p in listURL:
        return_code, _path = get_a_photo(p, album_name)
        if return_code == 0:
            print(f'{_path} 下载成功')
        elif return_code == 1:
            print(f'{_path} 已经存在')
        elif return_code == -1:
            print(f'{_path} 下载失败。')


def main(_url):
    start = time.time()
    get_album(_url)
    print(f'运行时间：{time.time()-start}')


if __name__ == '__main__':
    url = 'http://q1.fnmdsbb.xyz/pw/html_data/114/1911/4441681.html'
    main(url)
